'use strict';

const { logger } = require('ee-core/log');
const si = require('systeminformation');
const { Decimal } = require('decimal.js')
const wallpaper = require('wallpaper')
const { dialog } = require('electron')
const path = require('path')

/**
 * 系统服务
 * @class
 */
class SystemService {
    /**
     * getSysRunState
     * */
    async getSysRunState() {
        let result = await this.monitorSystem();
        console.log(result);
        return {
            cpu: result.filter(item => item.category === 'cpu'),
            memory: result.filter(item => item.category === 'memory'),
            disk: result.filter(item => item.category === 'disk')
        };
    }

    // 获取 CPU 使用情况
    async getCPUInfo() {
        const cpu = await si.currentLoad();
        console.log(`CPU Usage: ${cpu.currentLoad.toFixed(2)}%`);
        return [{
            category: 'cpu',
            label: "系统 CPU 使用率",
            name: "cpu",
            value: cpu.currentLoad.toFixed(2)
        }];
    }

    // 获取内存使用情况
    async getMemoryInfo() {
        const memory = await si.mem();
        console.log(`Memory Usage: ${(memory.used / memory.total * 100).toFixed(2)}%`);
        // console.log(Decimal(memory.used))
        return [
            {
                category: 'memory',
                label: "系统运行内存",
                name: "memoryTotal",
                value: (memory.total / (1024 * 1024 * 1024)).toFixed(2) + 'G'
            },
            {
                category: 'memory',
                label: "系统已用内存",
                name: "memoryUsed",
                value: `${(memory.used / memory.total * 100).toFixed(2)*1}`
            }
        ];
    }

    // 获取硬盘使用情况
    async getDiskInfo() {
        const disks = await si.fsSize();
        let _disks_details_list = [];
        disks.forEach(disk => {
            console.log(`Disk ${disk.fs}: ${disk.used / disk.size * 100}% used`);
            _disks_details_list.push({
                category: 'disk',
                label: `磁盘 ${disk.fs} `,
                name: disk.fs,
                fs: disk.fs,
                used: disk.used,
                size: disk.size,
                value: ((disk.used / disk.size * 100).toFixed(2)*1)
            });
        });
        return [{
            category: 'disk',
            label: "系统硬盘使用情况",
            name: "disk",
            value: _disks_details_list
        }];
    }

    async monitorSystem() {
        let cpuInfo = await this.getCPUInfo();
        let memoryInfo = await this.getMemoryInfo();
        let diskInfo = await this.getDiskInfo();
        return [...cpuInfo, ...memoryInfo, ...diskInfo];
    }
    
    /**
    * 设置壁纸服务
    */
    async setWallpaper(){
        return  await dialog.showOpenDialog({
            title:"选择文件",
            properties: ['openFile'],
        }).then(async result => {
           if(!result.canceled){
               const filePath = result.filePaths[0]
               logger.info('选择的壁纸文件路径为 ---> ', filePath)
               try {
                   let done = await wallpaper.setWallpaper(filePath)
                   console.log('壁纸设置进度',done)
                   return { code: 200, msg: '设置壁纸成功',data: filePath}
               }catch (e) {
                   logger.error('设置壁纸失败', e)
                   return { code: 400, msg: '设置壁纸失败'}
               }
           }
        }).catch(err => {
            logger.error('打开文件时发生错误', err)
            return { code: 400, msg: '打开文件时发生错误' }
        })
    }

    async getWallpaper(){
        let wallpaperPath = await wallpaper.getWallpaper()
        return wallpaperPath
    }
}
SystemService.toString = () => '[class SystemService]';

module.exports = {
    SystemService,
    systemService: new SystemService()
};